import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wanandroid_ohos/pigeon/messages.g.dart';
import 'package:get/get.dart';

import 'channel_logic.dart';

class ChannelPage extends StatefulWidget {
  ChannelPage({Key? key}) : super(key: key);

  @override
  State<ChannelPage> createState() => _ChannelPageState();
}

class _ChannelPageState extends State<ChannelPage> {
  final ChannelLogic logic = Get.put(ChannelLogic());

  final ExampleHostApi _hostApi = ExampleHostApi();
  String? _hostCallResult;

  final ExampleHostApi _api = ExampleHostApi();

  Future<int> add(int a, int b) async {
    try {
      return await _api.add(a, b);
    } catch (e) {
      return 0;
    }
  }

  Future<bool> sendMessage(String messageText) {
    final MessageData message = MessageData(
        code: Code.one,
        data: <String?, String?>{'header': 'this is a header'},
        description: 'uri text');
    try{
      return _api.sendMessage(message);
    }catch (e){
      return Future(() => true);
    }
  }

  @override
  void initState() {
    super.initState();
    _hostApi.getHostLanguage().then((String response){
      setState(() {
        _hostCallResult = 'hello from $response';
      });
    }).onError<PlatformException>((PlatformException error, StackTrace _){
      setState(() {
        _hostCallResult = 'Failed to get host language: ${error.message}';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('Pigeon Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_hostCallResult ?? 'waiting for host language...'),
            if (_hostCallResult == null) const CircularProgressIndicator(),
            TextButton(onPressed: (){
              add(1, 2);
            }, child: Text('add')),
            TextButton(onPressed: (){
              sendMessage("messageText");
            }, child: Text('sendMessage')),
          ],
        ),
      ),
    );
  }
}
